package com.qire.manhua.view.comicReader.renderer.core;

import android.graphics.Bitmap;

import com.qire.manhua.view.comicReader.renderer.utils.Utils;

import java.lang.ref.SoftReference;

/**
 * Created by Administrator on 2018/9/13.
 */

public class SoftLruMemoryCacheImpl implements IMemoryCache {

    private final LruMemoryCache<String, BitmapSoftReference> mMemoryCache;

    public SoftLruMemoryCacheImpl(int size) {
        mMemoryCache = new LruMemoryCache<String, BitmapSoftReference>(size) {
            @Override
            protected int sizeOf(String key, BitmapSoftReference bitmap) {
                return bitmap.size;
            }
        };
    }

    @Override
    public void put(String key, Bitmap bitmap) {
        mMemoryCache.put(key, new BitmapSoftReference(bitmap));
    }

    @Override
    public Bitmap get(String key) {
        BitmapSoftReference memBitmap = mMemoryCache.get(key);
        if(memBitmap!=null){
            return memBitmap.get();
        }
        return null;
    }

    @Override
    public void evictAll() {
        mMemoryCache.evictAll();
    }

    @Override
    public void remove(String key) {
        mMemoryCache.remove(key);
    }



    public class BitmapSoftReference extends SoftReference<Bitmap> {
        private final int size;
        public BitmapSoftReference(Bitmap referent) {
            super(referent);
            size = Utils.getBitmapSize(referent);
        }
    }

}
